package com.sd365.gateway.core.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;

@Slf4j

public class HttpsAndHttp {
    @PostConstruct
    public void startRedirectServer() {
        NettyReactiveWebServerFactory httpNettyReactiveWebServerFactory = new NettyReactiveWebServerFactory(8080);
        httpNettyReactiveWebServerFactory.getWebServer(
                (request, response) -> {
                    URI uri = request.getURI();
                    URI httpsUri;
                    try {
                        httpsUri = new URI("https", uri.getUserInfo(), uri.getHost(), 8081, uri.getPath(), uri.getQuery(), uri.getFragment());
                        log.info(httpsUri.toString());
                    } catch (URISyntaxException e) {
                        return Mono.error(e);
                    }
                    response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                    response.getHeaders().setLocation(httpsUri);
                    return response.setComplete();
                }).start();
    }
}
